<template>
  <view>
    <TopNavigation title="分组管理" backText="房间列表" />
    <view class="view-container">
      <view class="view-container-right">
        <view class="view-container-right-add">

          <text style="margin-right: 10rpx;" @click="openAddRuleModal">创建分组</text>
          <text @click="loadGroupList">刷新分组</text>
        </view>
        <BoxView :titBoxObj="{
          title: '分组列表',
          titleCount: `共有${groupList.length}个分组`
        }" padding="0" style="background: #FFFFF4;">
          <view class="view-container-right-tit">
            <view>房间名称：<text>{{ roomName }}</text></view>
            <view>房间ID：<text>{{ roomId }}</text></view>
          </view>
          <view class="view-container-right-list">
            <view class="view-container-right-list-item-empty"
              v-if="groupList.length === 0 && !isAddingNewRule && !loading">
              <text>暂无分组</text>
            </view>
            <view class="view-container-right-list-item-empty" v-if="loading">
              <text>加载中...</text>
            </view>
            <!-- 新增规则表单 -->
            <view v-if="isAddingNewRule" class="view-container-right-list-item view-container-right-list-add">
              <view class="view-container-right-list-item-title">
                <view class="next-row ">
                  <view class="id-value" style="width: 50%;">
                    <text class="form-label">分组名称：</text>
                    <input v-model="formData.name" placeholder="请输入分组名称，如：A组、B组" class="form-input" />
                  </view>
                </view>
                <view class="next-row">
                  <view class="id-value" style="width: 50%;">
                    <text class="form-label">分组标签：</text>
                    <input v-model="formData.tag" placeholder="请输入分组标签，如：group_a、group_b" class="form-input" />
                  </view>
                </view>
                <view class="next-button">
                  <view class="next-button-item1" @click.stop="submitForm">提交</view>
                  <view class="next-button-item2" @click.stop="closeModal">取消</view>
                </view>
              </view>
            </view>
            <view v-if="!loading && groupList.length > 0" class="view-container-right-list-item"
              :class="{ 'view-container-right-list-item-editing': editingRuleId === group.id }"
              v-for="group in groupList" :key="group.id">
              <view class="view-container-right-list-item-title">
                <!-- 编辑状态 -->
                <template v-if="editingRuleId === group.id">
                  <view class="next-row">
                    <view class="id-text"><text class="rule-id-disabled">规则ID：</text><text class="rule-id-disabled">{{
                      group.id }}</text></view>

                  </view>
                  <view class="next-row">
                    <view class="id-text" style="width: 50%;">
                      <text class="form-label">分组名称：</text>
                      <input v-model="formData.name" placeholder="请输入分组名称，如：A组、B组" class="form-input" />
                    </view>
                    <view class="id-text" style="width: 50%;">
                      <text class="form-label">分组标签：</text>
                      <input v-model="formData.tag" placeholder="请输入分组标签，如：group_a、group_b" class="form-input" />
                    </view>
                  </view>
                  <view class="next-button">
                    <view class="next-button-item1" @click.stop="submitForm">保存</view>
                    <view class="next-button-item2" @click.stop="closeModal">取消</view>
                  </view>
                </template>
                <!-- 查看状态 -->
                <template v-else>
                  <view class="next-row">
                    <view class="id-text"><text>分组ID：</text>{{ group.id }}</view>
                    <view class="group-status" :class="getStatusClass(group.delFlag)">
                      {{ getStatusText(group.delFlag) }}</view>
                  </view>
                  <view class="next-row">
                    <view class="id-value"><text>分组名称：</text>{{ group.name }}</view>
                    <view class="id-text"><text>分组标签：</text>{{ group.tag || '无' }}</view>
                  </view>

                  <view class="next-row">
                    <view class="id-text"><text>房间ID：</text>{{ group.matchRoomId }}</view>
                    <view class="id-text"><text>创建时间：</text>{{ formatDate(group.createTime) }}</view>
                  </view>
                  <view class="next-row">
                    <view class="id-text"><text>更新时间：</text>{{ formatDate(group.updateTime) }}</view>
                  </view>
                  <view class="next-button">
                    <view class="next-button-item1" @click.stop="editGroup(group)">编辑</view>
                    <view class="next-button-item2" @click.stop="deleteGroup(group)">删除</view>
                  </view>
                </template>
              </view>
            </view>
          </view>

        </BoxView>
      </view>
    </view>
  </view>

</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { MatchRoomGroupAPI } from '@/api/battle.js'
import BoxView from "@/components/UiView/BoxView.vue";
import TopNavigation from "@/components/UiView/TopNavigation.vue";

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const roomId = ref('')
const roomName = ref('')
const groupList = ref([])

// 模态框相关
const showModal = ref(false)
const isEdit = ref(false)
const formData = ref({
  matchRoomGroupId: '',
  matchRoomId: '',
  name: '',
  tag: ''
})

// 状态映射
const statusMap = {
  0: '有效',
  1: '已删除'
}

const statusClassMap = {
  0: 'status-valid',
  1: 'status-deleted'
}
const isAddingNewRule = ref(false)
const editingRuleId = ref(null)
const ruleForm = ref({
  startPoint: '',
  endPoint: '',
  prepareTimeSeconds: '',
  limitTimeSeconds: '',
  round: '',
  scoreModel: 0,
  battleModel: 0
})
// 获取状态文本
const getStatusText = (delFlag) => statusMap[delFlag] || '未知'

// 获取状态样式
const getStatusClass = (delFlag) => statusClassMap[delFlag] || 'status-unknown'
// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '未设置'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN')
}
const openAddRuleModal = () => {
  isAddingNewRule.value = true
  resetForm()
}

// 加载分组列表
const loadGroupList = async () => {
  if (!roomId.value) return

  loading.value = true
  try {
    console.log('加载分组列表，房间ID:', roomId.value)

    const result = await MatchRoomGroupAPI.page({
      matchRoomId: roomId.value,
      pageNum: 0,
      pageSize: 100
    })

    console.log('分组列表API返回结果:', result)

    if (result.code === 0) {
      groupList.value = result.data || []
      console.log('获取到分组列表:', groupList.value)
    } else {
      groupList.value = []
      throw new Error(result.msg || '获取分组列表失败')
    }
  } catch (error) {
    console.error('获取分组列表失败:', error)
    uni.showToast({
      title: error.message || '获取分组列表失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}


// 编辑分组
const editGroup = (group) => {
  isEdit.value = true
  editingRuleId.value = group.id
  formData.value = {
    matchRoomGroupId: group.id,
    matchRoomId: group.matchRoomId,
    name: group.name || '',
    tag: group.tag || ''
  }
}

// 删除分组
const deleteGroup = (group) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除分组 "${group.name}" 吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await MatchRoomGroupAPI.remove({
            matchRoomGroupId: group.id
          })

          if (result.code === 0) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
            loadGroupList()
          } else {
            throw new Error(result.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除分组失败:', error)
          uni.showToast({
            title: error.message || '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 关闭模态框
const closeModal = () => {
  isAddingNewRule.value = false
  resetForm()
  editingRuleId.value = null
}

// 重置表单
const resetForm = () => {
  formData.value = {
    matchRoomGroupId: '',
    matchRoomId: roomId.value,
    name: '',
    tag: ''
  }
}

// 提交表单
const submitForm = async () => {
  // 表单验证
  if (!formData.value.name.trim()) {
    uni.showToast({
      title: '请输入分组名称',
      icon: 'none'
    })
    return
  }

  submitting.value = true
  try {
    const api = isEdit.value ? MatchRoomGroupAPI.edit : MatchRoomGroupAPI.create
    const submitData = { ...formData.value }

    const result = await api(submitData)

    if (result.code === 0) {
      uni.showToast({
        title: isEdit.value ? '更新成功' : '创建成功',
        icon: 'success'
      })
      closeModal()
      loadGroupList()
    } else {
      throw new Error(result.msg || (isEdit.value ? '更新失败' : '创建失败'))
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    uni.showToast({
      title: error.message || (isEdit.value ? '更新失败' : '创建失败'),
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}


// 页面加载
onLoad((options) => {
  if (options.roomId) {
    roomId.value = options.roomId
  }
  if (options.roomName) {
    roomName.value = decodeURIComponent(options.roomName)
  }
})

// 页面挂载时加载数据
onMounted(() => {
  loadGroupList()
})
</script>

<style lang="scss" scoped>
.form-input {
  // flex: 1;
  height: 30rpx;
  padding: 0 5rpx;
  background: #fff;
  border-radius: 4rpx;
  font-size: 12rpx;
  margin-left: 10rpx;
  margin-right: 20rpx;
  box-sizing: border-box;
}

.group-status {
  padding: 3rpx 12rpx;
  border-radius: 16rpx;
  font-size: 12rpx;
  font-weight: bold;

  &.status-valid {
    background: #d4edda;
    color: #155724;
  }

  &.status-deleted {
    background: #f8d7da;
    color: #721c24;
  }
}

.view-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: calc(100vh - 65rpx);
  padding-right: 20rpx;
  padding-left: 20rpx;
  overflow: hidden;

  &-right {
    flex: 1;
    height: 100%;
    overflow: hidden;
    position: relative;

    &-tit {
      display: flex;
      justify-content: space-between;
      align-items: center;
      // margin-bottom: 10rpx;
      padding: 4rpx 20rpx;
      font-size: 12rpx;
      color: #99A1A4;

      text {
        color: #000000;
      }
    }

    &-add {
      z-index: 1000;
      position: absolute;
      color: #fff;
      top: 8rpx;
      left: 10rpx;
      font-size: 12rpx;

      text {
        border-bottom: 1rpx solid #ff0000;
        color: #ff0000;

        &:last-child {
          color: #99ff00;
          border-bottom: 1rpx solid #99ff00;
        }
      }
    }

    &-list {
      padding: 10rpx;
      overflow: auto;
      height: calc(100% - 65rpx);

      &-add {
        background: #FFF9E6;
      }

      &-item {
        background: #F0F0E4;
        border-radius: 10rpx;
        padding: 10rpx;
        margin-bottom: 10rpx;
        font-size: 14rpx;

        &-empty {
          text-align: center;
          margin-top: 80rpx;
        }

        .next-button {
          display: flex;
          justify-content: end;
          align-items: center;
          margin-top: 10rpx;

          &-item1,
          &-item2 {
            width: 108rpx;
            height: 30rpx;
            font-size: 14rpx;
            display: flex;
            justify-content: center;
            align-items: center;
            padding-bottom: 4rpx;
            color: #fff;
          }


          &-item1 {
            background: url('/static/buttons/button2-1.png') no-repeat center center;
            background-size: 100% 100%;
            margin-right: 10rpx;
          }

          &-item2 {
            background: url('/static/buttons/button7.png') no-repeat center center;
            background-size: 100% 100%;
          }
        }

        .next-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: 10rpx;

          .id-text {
            display: flex;
            align-items: center;
          }

          text {
            display: inline-block;
            font-size: 14rpx;
            color: #99A1A4;
            width: 70rpx;
            text-align: right;
          }
        }
      }
    }
  }

}
</style>